<template>
  <!--库存流水-->
  <div class="inv">
    <!--仓库标签页-->
    <el-row>
      <el-tabs v-model="warehouseValue" @tab-click="changeWar(warehouseValue)">
        <el-tab-pane label="全部仓库" name="0"></el-tab-pane>
        <el-tab-pane
          :key="index"
          v-for="(item, index) in warehouseList"
          :label="item.warehouseName"
          :name="item.warehouseId+''">
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <!--库存查找-->
    <el-row>
      <span style="padding: 0 10px"><i class="font-14 el-icon-s-open"></i></span>
      <el-select v-model="filterValue" value-key="value" @change="initData(currPage,pageSize,warId,filterValue,content)" placeholder="全部数据" style="width: 120px">
        <el-option v-for="item in filterOptions" :key="item.value" :label="item.label" :value="item">
        </el-option>
      </el-select>
      <span style="padding: 0 10px 0 30px"><i class="fn el-icon-message-solid"></i></span>
      <el-input v-model="content" clearable placeholder="请输入内容" style="width: 150px"></el-input>
      <el-select v-model="vagueValue" placeholder="产品名" style="width: 120px">
        <el-option v-for="item in vagueOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button @click="initData(currPage,pageSize,warId,filterValue,content)" icon="el-icon-search" size="small" circle></el-button>
    </el-row>
    <!--库存流水数整理-->
    <div style="margin-top: 15px;overflow: hidden;">
      <el-col :span="12" class="m-b-10">
        <span>库存流水</span>
        <small class="text-muted font-13">共{{totalSize}}条</small>
      </el-col>
      <!--入库单dialog-->
      <el-dialog title="入库单" :visible.sync="dialogSto" @close="closeDialogSto" width="60%" style="color: #333333"  >
        <el-form :model="storage" label-width="100px">
          <el-divider></el-divider>
          <el-row>
            <el-col>
              <el-form-item label="主题:">
                <el-input v-model="storage.storageTheme" style="width: 91%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仓库:">
                <el-select v-model="storage.warehouseByWarehouseId" value-key="warehouseId" placeholder="未选" style="width: 79%">
                  <el-option :disabled="true" v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填单时间:">
                <el-input :disabled="true" v-model="storage.storageDate" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态:">
                <el-select v-model="storage.storageStatus" placeholder="未选" style="width: 79%">
                  <el-option :disabled="true" v-for="item in ztsOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填单人:">
                <el-input :disabled="true" v-model="storage.employeeByStoEmployeeId.empName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="库管确认:">
                <el-input v-if="this.storage.employeeByAffEmployeeId !== null" :disabled="true" v-model="storage.employeeByAffEmployeeId.empName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行时间:">
                <el-input :disabled="true" v-model="storage.storageExecutorDate" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对应采购单:">
                <el-input :disabled="true" v-model="storage.purchaseByPurchaseId.purchaseTheme" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对应退货单:">
                <el-input v-if="this.storage.returnByReturnId !== null" :disabled="true" v-model="storage.returnByReturnId.returnTheme" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="对应供应商:">
                <el-input :disabled="true" v-model="storage.customerByCustomerId.customerName" style="width: 79%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="备注:">
                <el-input v-model="storage.storageNote" style="width: 91%" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="入库明细:" style="width: 92%">
                <el-row>
                  <el-row>
                    <el-col :span="4" :offset="12">
                    </el-col>
                  </el-row>
                  <div>
                    <el-table :data="storage.storageDetailsByStorageId" style="width: 100%" border show-summary>
                      <el-table-column type="index" label="序号" width="50">
                      </el-table-column>
                      <el-table-column prop="productByProductId.productName" label="产品名" >
                      </el-table-column>
                      <el-table-column prop="productByProductId.productModel" label="型号" >
                      </el-table-column>
                      <el-table-column prop="storageDetailNum" label="入库量" >
                      </el-table-column>
                      <el-table-column prop="storageDetailNote" label="备注" >
                      </el-table-column>
                    </el-table>
                  </div>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="8">
              <el-form-item>
                <span v-if="this.storage.storageStatus === 1">
                   <el-button @click="addStorage" type="primary">保存</el-button>
                  <el-button @click="dialogFormVisible = false">取消</el-button>
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <!--库存流水表格-->
    <el-table ref="multipleTable" :data="inventoryFlowList" tooltip-effect="dark" id="outTable"
              style="width: 100%" border :header-cell-style="rowClass">
      <el-table-column prop="inventoryFlowId" label="ID" sortable width="100"></el-table-column>
      <el-table-column prop="inventoryFlowClassify" label="类型" >
        <template slot-scope="scope">
          <span v-if="scope.row.inventoryFlowClassify === 1">入库</span>
          <span v-if="scope.row.inventoryFlowClassify === 2">出库</span>
        </template>
      </el-table-column>
      <el-table-column prop="storageByStorageId.warehouseByWarehouseId.warehouseName" label="仓库" >
      </el-table-column>
      <el-table-column label="产品名称" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.productByProductId.productName}}</span>
          <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
            <router-link :to="{path:'/customerview',query: {productId: scope.row.productByProductId.productId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
            </router-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="入库量" >
        <template slot-scope="scope">
          <span v-if="scope.row.inventoryFlowClassify === 1">{{scope.row.stoDetailByStoDetailId.storageDetailNum}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inventoryNum" label="出库量" >
        <template slot-scope="scope">
          <span v-if="scope.row.inventoryFlowClassify === 1">0</span>
        </template>
      </el-table-column>
      <el-table-column prop="storageByStorageId.storageExecutorDate" sortable label="执行日期" >
        <template slot-scope="scope">
          <span>{{scope.row.storageByStorageId.storageExecutorDate | formatDateJudge}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" >
        <template slot-scope="scope">
          <span v-if="scope.row.storageByStorageId.storageStatus === 1">未执行</span>
          <span v-if="scope.row.storageByStorageId.storageStatus === 2">已执行</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商"  width="160">
        <template slot-scope="scope">
          <div style="color: #333333">
            <span>{{scope.row.storageByStorageId.customerByCustomerId.customerName}}</span>
            <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
              <router-link :to="{path:'/customerview',query: {customerId: scope.row.storageByStorageId.customerByCustomerId.customerId}}">
                <span style="color: #333333">
                  <i class="el-icon-s-cooperation"></i>
                </span>
              </router-link>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" width="105px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="查看对应单据" placement="bottom">
            <el-button size="mini" @click="handleEdit(scope.row)"
                       icon="el-icon-s-ticket" type="primary" circle style="margin-left: 10px"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="margin-top:10px">
      <el-col :offset="8" :span="14">
        <el-pagination layout="sizes,prev,pager, next, jumper" :total="totalSize" @current-change="changePage"
                       :current-page.sync="currPage" :page-size="pageSize" :page-sizes="pageSizes" @size-change="changeSize"></el-pagination>
      </el-col>
      <el-col :span="2">
        <el-tooltip class="item" effect="dark" content="打印列表" placement="bottom">
          <el-button @click="handleWindowPrint('#outTable', '列表打印')" style="padding: 12px 12px" type="info" plain  icon="el-icon-printer"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="导出Excel格式数据" placement="bottom">
          <el-button @click="exportExcel" style="padding: 12px 12px" type="info" plain  icon="el-icon-document-remove"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
  </div>

</template>

<script>
  import {formatTimeToStr} from "../assets/format";
  import XLSX from "xlsx";
  import FileSaver from "file-saver";

  export default {
  data () {
    return {
      dialogSto:false,
      emp:{},
      inventoryFlowList: [], // 库存集合分页
      warehouseList: [],// 仓库集合
      warehouseValue: '0',
      warId:0,// 默认仓库值
      pageSize: 10, // 分页页大小
      pageSizes:[10,20,30],//页大小数组
      currPage: 1, // 当前页码，默认为1
      totalSize: 0, // 总记录数
      storage: {
        storageId: 0,
        storageTheme: '',
        storageDate: '',
        storageStatus: '',
        storageNote: '',
        storageExecutorDate: '',
        customerByCustomerId: '',
        employeeByStoEmployeeId: '',
        employeeByAffEmployeeId: '',
        purchaseByPurchaseId: '',
        returnByReturnId: '',
        warehouseByWarehouseId: ''
      },
      stoDetailList: [],//明细集合
      content: '',// 按产品查询内容绑定值
      filterOptions: [{
        value: 0,
        label: '全部数据',
        num: 0
      },{
        value: 1,
        label: '入库',
        num: 1
      },{
        value: 2,
        label: '出库',
        num: 2
      },{
        value: 3,
        label: '退货',
        num: 3
      },{
        value: 4,
        label: '采购退货',
        num: 4
      },{
        value: 5,
        label: '未执行',
        num: 1
      },{
        value: 6,
        label: '已执行',
        num: 2
      }],
      filterValue: {value:0,num:0},
      vagueOptions: [{
        value: 1,
        label: '产品名'
      }],
      vagueValue: 1,
      ztsOptions: [{
        value: 1,
        label: '未入库'
      },{
        value: 2,
        label: '已入库'
      }],
    }
  },
  methods: {
    // 查询当前员工
    loginEmp(){
      this.$axios.get('http://localhost:8088/emp')
        .then(v => {
          this.emp = v.data
        })
        .catch(function (v) {})
    },
    // 分页查询所有库存
    initData (currPage, pageSize,warId,filter,content) {
      this.$axios.get('http://localhost:8088/inv-flow-list', {
        params: {
          page: currPage,
          size: pageSize,
          warId: warId,
          value: filter.value,
          num: filter.num,
          content:content
        }
      })
        .then(v => {
          this.inventoryFlowList = v.data.rows
          this.totalSize = v.data.total
        })
        .catch(function (v) {})
    },
    // 库存表格分页
    changePage (val) {
      this.initData(val, this.pageSize,this.warId,this.filterValue,this.content)
    },
    //改变页大小
    changeSize(val){
      this.pageSize = val
      this.currPage = 1
      this.initData(this.currPage, this.pageSize,this.warId,this.filterValue,this.content)
    },
    // 分页查询所有库存
    findWarehouse () {
      this.$axios.get('http://localhost:8088/war-list',)
        .then(v => {
          this.warehouseList = v.data
        })
        .catch(function (v) {})
    },
    // 修改数据回显
    handleEdit (val) {
      this.dialogSto = true
      if (val.inventoryFlowClassify === 1){
        this.findStorage(val.storageByStorageId.storageId)
        this.findStoDetail(val.storageByStorageId.storageId)
      }
    },
    // 查询入库单
    findStorage(stoId){
      this.$axios.get('http://localhost:8088/sto-id', {
        params: {
          stoId : stoId
        }
      })
        .then(v => {
          this.storage = v.data
          if (this.storage.employeeByAffEmployeeId === null){
            this.storage.employeeByAffEmployeeId = ''
          }
          if (this.storage.returnByReturnId === null){
            this.storage.returnByReturnId = ''
          }
        })
        .catch(function (v) {})
    },
    // 查询所有入库明细
    findStoDetail(stoId){
      this.$axios.get('http://localhost:8088/sto-detail-list', {
        params:{
          stoId : stoId
        }
      })
        .then(v => {
          this.stoDetailList = v.data
        })
        .catch(function (v) {})
    },
    // 关闭入库dialog事件
    closeDialogSto () {
      this.storage = {
        storageId: 0,
        storageTheme: '',
        storageDate: '',
        storageStatus: '',
        storageNote: '',
        storageExecutorDate: '',
        customerByCustomerId: '',
        employeeByStoEmployeeId: '',
        employeeByAffEmployeeId: '',
        purchaseByPurchaseId: '',
        returnByReturnId: '',
        warehouseByWarehouseId: ''
      }
    },
    // 选择仓库
    changeWar(val){
      this.warId = Number(val)
      this.initData(this.currPage,this.pageSize,this.warId,this.filterValue,this.content)
    },
    // 修改入库单
    addStorage() {
      if(this.storage.employeeByAffEmployeeId == ''){
        this.storage.employeeByAffEmployeeId = null
      }
      if(this.storage.returnByReturnId == ''){
        this.storage.returnByReturnId = null
      }
      this.$axios.post('http://localhost:8088/save-storage',
        {
          storageId: this.storage.storageId,
          storageTheme: this.storage.storageTheme,
          storageDate: this.storage.storageDate,
          storageStatus: this.storage.storageStatus,
          storageNote: this.storage.storageNote,
          storageExecutorDate: this.storage.storageExecutorDate,
          warehouseByWarehouseId: this.storage.warehouseByWarehouseId,
          employeeByStoEmployeeId: this.storage.employeeByStoEmployeeId,
          employeeByAffEmployeeId: this. storage.employeeByAffEmployeeId,
          purchaseByPurchaseId: this.storage.purchaseByPurchaseId,
          returnByReturnId: this.storage.returnByReturnId,
          customerByCustomerId: this.storage.customerByCustomerId,
          storageDetailsByStorageId: this.stoDetailList
        })
        .then(v => {
          this.dialogSto = false
          this.$message({
            message: '已保存',
            type: 'success'
          });
        })
        .catch(function (v) {
        })
    },
    // pdf打印
    handleWindowPrint (ele, fileName) {
      document.body.innerHTML = document.querySelector(ele).outerHTML
      // 转异步 等待dom元素渲染（样式）完毕在打印
      setTimeout(() => {
        // 打印
        window.print()
        // 刷新页面
        window.location.reload()
      }, 20)
    },
    //导出excel
    exportExcel () {
      var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "库存流水导出.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 表头靠左样式
    rowClass(){
      return "text-align:left"
    }
  },
  created() {
    this.loginEmp()
    this.initData(this.currPage,this.pageSize,this.warId,this.filterValue,this.content)
    this.findWarehouse()
  },
    filters: {
      formatDateJudge: function(time) {
        if(time != null && time != "")
        {
          let date = new Date(time);
          let currentDate = new Date()
          let seperator1 = "-";
          let month = currentDate.getMonth() + 1<10? "0"+(currentDate.getMonth() + 1):currentDate.getMonth() + 1;
          let strDate = currentDate.getDate()<10? "0" + currentDate.getDate():currentDate.getDate();
          let today = currentDate.getFullYear() + seperator1  + month  + seperator1  + strDate
          let todayTime = new Date(today)
          let yesterday = todayTime.setDate(todayTime.getDate() - 1)
          let beforeYesterday = todayTime.setDate(todayTime.getDate() - 1)
          let tomorrow = todayTime.setDate(todayTime.getDate() + 3)
          let afterTomorrow = todayTime.setDate(todayTime.getDate() + 1)
          todayTime.setDate(todayTime.getDate() - 2)
          if (date.getTime() === todayTime.getTime()){
            return '今天'
          }else if (date.getTime() ===  yesterday){
            return '昨天'
          }else if (date.getTime() ===  beforeYesterday){
            return '前天'
          }else if (date.getTime() ===  tomorrow){
            return '明天'
          }else if (date.getTime() ===  afterTomorrow){
            return '后天'
          }else {
            return time
          }
        }else{
          return "";
        }
      }
    }
}
</script>

<style>

</style>
